<?php

/**
 * basic template class
 *
 * @author ecv
 */
class Tmpl extends File {

    public $targets;
    public $output;

    /**
     * Alle Template Tags auslesen
     */
    function get_targets()
    {
        if ($this->load_file())
        {
            if (!isset($this->output) || empty($this->output))
            {
                $this->output = $this->source;
            }
            preg_match_all("|{##.*?##}|", $this->output, $this->targets['area']);
            preg_match_all("|{##.*?##/}|", $this->output, $this->targets['single']);

            return TRUE;
        }
        else
        {
            return FALSE;
        }
    }

    function replace_targets($data = array())
    {
        if ($this->load_file())
        {
            if (!isset($this->output) || empty($this->output))
            {
                $this->output = $this->source;
            }
            if (count($this->targets['area'][0]) >= 1)
            {
                foreach ($this->targets['area'][0] as $index => $tag)
                {
                    if (!empty($data[$tag]))
                    {
                        $regex = "|" . $tag . "(.*?)" . str_replace("{##", "{/##",
                                $tag) . "|is";
                        $this->output = preg_replace(str_replace(array('{', '}'),
                                array('\{', '\}'), $regex), $data[$tag],
                            $this->output);
                    }
                }
            }
            if (count($this->targets['single'][0]) >= 1)
            {
                foreach ($this->targets['single'][0] as $index => $tag)
                {
                    if (!empty($data[str_replace('/}', '}', $tag)]))
                    {
                        $regex = "|" . $tag . "|";
                        $this->output = preg_replace(str_replace(array('{', '}'),
                                array('\{', '\}'), $regex),
                            $data[str_replace('/}', '}', $tag)], $this->output);
                    }
                }
            }

            return TRUE;
        }
        else
        {
            return FALSE;
        }
    }

    function strip_targets()
    {
        if ($this->load_file())
        {
            if (!isset($this->output) || empty($this->output))
            {
                $this->output = $this->source;
            }
            $this->output = preg_replace("|{.*?}|", '', $this->output);
            return TRUE;
        }
        else
        {
            return FALSE;
        }
    }

    function tidy_up()
    {
        if ($this->load_file())
        {
            if (!isset($this->output) || empty($this->output))
            {
                $this->output = $this->source;
            }

            return TRUE;
        }
        else
        {
            return FALSE;
        }
    }

}